/**
 * Copyright (c) 2010 Basil Shikin, BugStat Project
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.bugstat.generators.reports.generators;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bugstat.common.TimeInterval;
import org.bugstat.common.bugs.Bug;
import org.bugstat.common.reports.Report;
import org.bugstat.generators.CanGenerateReports;
import org.bugstat.generators.GeneratorsStrings;
import org.bugstat.generators.ReportGeneratorContext;
import org.bugstat.generators.reports.ReportGeneratorBase;
import org.bugstat.generators.reports.TimedIntegerReport;

/**
 * This is a generator of how long it takes to get a bug fixed report 
 *
 * @author Basil Shikin
 */
@CanGenerateReports
public class OpenBugsAge
    extends ReportGeneratorBase
{
    private final TimedIntegerReport report;
        
    private final Collection<Integer> currentlyClosedBugIDs = new ArrayList<Integer>( 15 );    
    private final Map<Integer, Integer> openBugAges = new HashMap<Integer,Integer>(); // Bug ID -> Number of days open
    
    public OpenBugsAge()
    {
        setName( GeneratorsStrings.TEXT_OPEN_BUGS_AGE );
        
        report = new TimedIntegerReport();
        
        report.setName( GeneratorsStrings.TEXT_OPEN_BUGS_AGE );
        report.setGroup( GeneratorsStrings.TEXT_GROUP_OVERVIEW );
        report.setValueName( GeneratorsStrings.TEXT_NO_OF_DAYS_OPEN );
        report.setVisibleByDefault( true );
    }
    
    @Override
    public void startedGeneratingReports( TimeInterval timeInterval, ReportGeneratorContext context )
    {
        super.startedGeneratingReports(timeInterval, context);
        
        report.setTimeInterval( timeInterval );
        report.clear();        
    }
    
    @Override
    public void periodStarted(Date startDate)
    {
        super.periodStarted( startDate );
        
        currentlyClosedBugIDs.clear();
    }

    @Override
    public void periodEnded()
    {
        super.periodEnded();
        
        float averageBugAge = 0;
        for ( Integer bugAge : openBugAges.values() )
        {
            averageBugAge += bugAge;
        }
        averageBugAge = averageBugAge / openBugAges.size();
        
        report.putValue( currentDate, normalizeBugAge( averageBugAge, currentInterval ) );
        
        // Now, remove all closed bugs from open bugs durations
        for ( Integer bugID : currentlyClosedBugIDs )
        {
            openBugAges.remove( bugID );
        }
    }

    @Override
    public void processBug(Bug bug)
    {
        if ( !bug.isEnhancement() )
        {
            final int bugID = bug.getId();
            
            if ( bug.isOpen() )
            {
                Integer currentOpenDays = openBugAges.get( bugID );
                if ( currentOpenDays == null ) currentOpenDays = 0;
                
                openBugAges.put( bugID, currentOpenDays + 1 );
            }
            else if ( openBugAges.containsKey( bugID ) )
            {
                currentlyClosedBugIDs.add( bugID );
            }
        }
    }

    @Override
    public List<Report> getGeneratedReports()
    {
        return Arrays.asList( (Report)report );
    }
    
    static int normalizeBugAge( final float daysToFix, final TimeInterval timeInterval )
    {
        final float multiplier;
        switch ( timeInterval.getTimeStep() )
        {
            case MONTH: multiplier = 30; break;
            case WEEK: multiplier = 7; break;
            default: multiplier = 1;
        }
        
        final float actualDaysToFix = multiplier*daysToFix;
        return Math.round( actualDaysToFix < 1 ? 1 : actualDaysToFix );
    }
}